﻿using ExcelParser.Writer;
using System;
using System.Collections;
using System.Reflection;

namespace ExcelParser.CodeGen
{
    public class ArrayField : ExcelField
    {
        public ArrayField(string name, string desc) : base(string.Empty, name, desc) { }

        public override int MaxChildrenCount { get { return 1; } }

        public override void GenClass(CodeWriter writer)
        {
            base.GenClass(writer);
            for (int i = 0; i < m_children.Count; i++)
            {
                m_children[i].GenClass(writer);
            }
        }
        public override void GenCode(CodeWriter writer)
        {
            base.GenCode(writer);
            string fieldName = "m_" + Name.Substring(0, 1).ToLower() + Name.Substring(1);
            writer.WriteLine("private List<{0}> {1};", writer.ConvertType(m_children[0].Type), fieldName);
            writer.WriteLine("public List<{0}> {1}", writer.ConvertType(m_children[0].Type), Name);
            writer.WriteLine("{{");
            writer.Indent++;
            writer.WriteLine("get {{ return {0}; }}", fieldName);
            writer.WriteLine("set {{ {0} = value; }}", fieldName);
            writer.Indent--;
            writer.WriteLine("}}");
        }

        public override void ParseValue(CodeWriter writer, object obj, PropertyInfo propertyInfo, MethodInfo methodInfo, Type fieldType, string value)
        {
            IList list = Activator.CreateInstance(fieldType) as IList;

            if (!string.IsNullOrEmpty(value))
            {
                string[] values = value.Split(';');
                MethodInfo addMethod = list.GetType().GetMethod("Add");
                for (int i = 0; i < values.Length; i++)
                {
                    m_children[0].ParseValue(writer, list, null, addMethod, addMethod.GetParameters()[0].ParameterType, values[i]);
                }
            }

            if (propertyInfo != null)
            {
                propertyInfo.SetValue(obj, list, null);
            }
            if (methodInfo != null)
            {
                methodInfo.Invoke(obj, new object[] { list });
            }
        }
    }
}